package com.cdu.guoxinan.www.smartcom.controller;

import com.cdu.guoxinan.www.smartcom.aop.Annotation.OperationLog;
import com.cdu.guoxinan.www.smartcom.domian.dto.OrderDTO;
import com.cdu.guoxinan.www.smartcom.domian.pojo.Order;
import com.cdu.guoxinan.www.smartcom.domian.pojo.OrderItem;
import com.cdu.guoxinan.www.smartcom.service.OrderService;
import com.cdu.guoxinan.www.smartcom.unit.model.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/order")
@Api(tags = "订单控制器")
public class OrderController {
    
    @Resource
    private OrderService orderService;
    
    /**
     * 创建订单
     */
    @PostMapping("/create")
    @ApiOperation("创建订单")
    @OperationLog(description = "创建订单")
    public R createOrder(@RequestBody OrderDTO orderDTO) {
        try {
            if (orderDTO.getUserId() == null) {
                return R.error("用户ID不能为空");
            }
            if (orderDTO.getItems() == null || orderDTO.getItems().isEmpty()) {
                return R.error("订单商品不能为空");
            }
            if (orderDTO.getDeliveryAddress() == null || orderDTO.getDeliveryAddress().trim().isEmpty()) {
                return R.error("收货地址不能为空");
            }
            if (orderDTO.getPhoneNumber() == null || orderDTO.getPhoneNumber().trim().isEmpty()) {
                return R.error("联系电话不能为空");
            }
            
            Order order = orderService.createOrder(orderDTO);
            return R.ok(order);
        } catch (Exception e) {
            return R.error("创建订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据用户ID查询订单列表
     */
    @GetMapping("/list")
    @ApiOperation("根据用户ID查询订单列表")
    public R getOrdersByUserId(@RequestParam Long userId) {
        try {
            if (userId == null) {
                return R.error("用户ID不能为空");
            }
            List<Order> orders = orderService.getOrdersByUserId(userId);
            return R.ok(orders);
        } catch (Exception e) {
            return R.error("查询订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 根据订单ID查询订单商品详情
     */
    @GetMapping("/items")
    @ApiOperation("根据订单ID查询订单商品详情")
    public R getOrderItems(@RequestParam Long orderId) {
        try {
            if (orderId == null) {
                return R.error("订单ID不能为空");
            }
            List<OrderItem> items = orderService.getOrderItemsByOrderId(orderId);
            return R.ok(items);
        } catch (Exception e) {
            return R.error("查询订单商品详情失败：" + e.getMessage());
        }
    }
    
    /**
     * 支付订单
     */
    @PostMapping("/pay")
    @ApiOperation("支付订单")
    public R payOrder(@RequestParam Long orderId) {
        try {
            if (orderId == null) {
                return R.error("订单ID不能为空");
            }
            boolean success = orderService.payOrder(orderId);
            if (success) {
                return R.ok("支付成功");
            } else {
                return R.error("支付失败，订单可能不存在或状态异常");
            }
        } catch (Exception e) {
            return R.error("支付失败：" + e.getMessage());
        }
    }
    
    /**
     * 取消订单
     */
    @PostMapping("/cancel")
    @ApiOperation("取消订单")
    @OperationLog(description = "取消订单")
    public R cancelOrder(@RequestParam Long orderId) {
        try {
            if (orderId == null) {
                return R.error("订单ID不能为空");
            }
            boolean success = orderService.cancelOrder(orderId);
            if (success) {
                return R.ok("订单已取消");
            } else {
                return R.error("取消失败，订单可能不存在或状态异常");
            }
        } catch (Exception e) {
            return R.error("取消订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 删除订单
     */
    @PostMapping("/delete")
    @ApiOperation("删除订单")
    @OperationLog(description = "删除订单")
    public R deleteOrder(@RequestParam Long orderId) {
        try {
            if (orderId == null) {
                return R.error("订单ID不能为空");
            }
            boolean success = orderService.deleteOrder(orderId);
            if (success) {
                return R.ok("订单已删除");
            } else {
                return R.error("删除失败，订单可能不存在或状态不允许删除");
            }
        } catch (Exception e) {
            return R.error("删除订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 完成订单
     */
    @PostMapping("/complete")
    @ApiOperation("完成订单")
    @OperationLog(description = "完成订单")
    public R completeOrder(@RequestParam Long orderId) {
        try {
            if (orderId == null) {
                return R.error("订单ID不能为空");
            }
            boolean success = orderService.completeOrder(orderId);
            if (success) {
                return R.ok("订单已完成");
            } else {
                return R.error("操作失败，订单可能不存在或状态不允许完成");
            }

        } catch (Exception e) {
            return R.error("完成订单失败：" + e.getMessage());
        }
    }
    
    /**
     * 分页查询所有订单（管理端用）
     */
    @GetMapping("/listAll")
    @ApiOperation("分页查询所有订单")
    public Map<String, Object> getAllOrders(@RequestParam(defaultValue = "1") int page,
                                           @RequestParam(defaultValue = "10") int limit,
                                           @RequestParam(required = false) String field,
                                           @RequestParam(required = false) String order) {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Order> orders = orderService.getAllOrdersWithPagination(page, limit, field, order);
            int count = orderService.countAllOrders();
            
            // 返回Layui表格需要的格式
            result.put("code", 0);
            result.put("msg", "");
            result.put("count", count);
            result.put("data", orders);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("msg", "查询订单失败：" + e.getMessage());
            result.put("count", 0);
            result.put("data", null);
        }
        return result;
    }
} 